/**
 * 
 */
package com.maywide.jdp.system.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.maywide.jdp.core.exception.AppException;
import com.maywide.jdp.core.vo.Context;
import com.maywide.jdp.core.vo.Page;
import com.maywide.jdp.system.annotation.JSON;
import com.maywide.jdp.system.bean.ModuleBean;
import com.maywide.jdp.system.entities.Module;
import com.maywide.jdp.system.entities.Role;
import com.maywide.jdp.system.utils.JSONEditor;
import com.maywide.jdp.system.vo.ModuleCheckedTree;
import com.maywide.jdp.system.vo.ModuleTree;

/**
 * 子系统管理Service
 * 
 * @author luoyang
 * @version 1.0
 * @since JDK1.6
 */
@Controller("moduleService")
public class ModuleServiceImpl implements ModuleService {
	private static final String APP_TYPE_BASE = "base";
	private static final String APP_TYPE_ROLES = "roles";
	/**
	 * 模块管理Bean接口
	 */
	private ModuleBean bean = null;

	/**
	 * @param bean
	 *            the bean to set
	 */
	@Autowired
	@Qualifier("moduleBean")
	public void setBean(ModuleBean bean) {
		this.bean = bean;
	}

	@JSON
	@RequestMapping(value = "/system/module/insert.json")
	@Override
	public Module insert(@RequestParam(value = "module") Module module,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.insert(module);
		return module;
	}

	@JSON
	@RequestMapping(value = "/system/module/update.json")
	@Override
	public Module update(@RequestParam(value = "module") Module moduleVO,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		String id = moduleVO.getId();
		Module module = (Module) bean.load(id);
		// 取得不可改变属性
		Module parent = module.getParent();
		List<Module> subs = module.getSubs();

		moduleVO.setParent(parent);
		moduleVO.setSubs(subs);
		BeanUtils.copyProperties(moduleVO, module);

		bean.update(module);
		return module;
	}

	@JSON
	@RequestMapping(value = "/system/module/updateApp.json")
	@Override
	public Module updateApp(@RequestParam(value = "module") Module moduleVO,
			@RequestParam(value = "appType") String appType,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		String id = moduleVO.getId();

		if (appType.equals(APP_TYPE_BASE)) {
			// 取得不可改变属性
			Module module = (Module) bean.load(id);
			Module parent = module.getParent();
			List<Module> subs = module.getSubs();
			List<Role> roles = module.getRoles();

			moduleVO.setParent(parent);
			moduleVO.setSubs(subs);
			moduleVO.setRoles(roles);
			BeanUtils.copyProperties(moduleVO, module);

			bean.update(module);
			return module;
		} else if (appType.equals(APP_TYPE_ROLES)) {
			List<Role> roles = moduleVO.getRoles();
			Module module = (Module) bean.load(id);
			module.setRoles(roles);
			bean.update(module);
			return module;
		} else {
			throw new AppException("未知的应用类型!");
		}
	}

	@JSON
	@RequestMapping(value = "/system/module/load.json")
	@Override
	public Module load(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Module module = (Module) bean.load(id);
		return module;
	}

	@RequestMapping(value = "/system/module/lock.json")
	@Override
	public void lock(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.lock(id);
	}

	@RequestMapping(value = "/system/module/unlock.json")
	@Override
	public void unlock(@RequestParam(value = "id") String id,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.unlock(id);
	}

	@RequestMapping(value = "/system/module/move.json")
	@Override
	public void move(@RequestParam(value = "ids") List<String> ids,
			@RequestParam(value = "targetID") String parentID,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		bean.move(ids, parentID);
	}

	@JSON
	@RequestMapping(value = "/system/module/page.json")
	public Page page(
			@RequestParam(value = "first", defaultValue = "0") int first,
			@RequestParam(value = "limit", defaultValue = "20") int limit,
			@RequestParam(value = "sort", required = false) String sort,
			@RequestParam(value = "dir", required = false) String dir,
			@RequestParam(value = "parentID", required = false) String parentID,
			@RequestParam(value = "key", required = false) String key,
			@RequestParam(value = "active", required = false) String active,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();
		if (key != null) {
			key = new StringBuffer("%").append(key).append("%").toString();
			conditions.put("key", key);
		}

		if (active != null)
			conditions.put("active", Boolean.parseBoolean(active));

		if (parentID != null && !"module_root".equals(parentID))
			conditions.put("parentID", parentID);
		else
			conditions.put("noParentID", null);

		Context context = (Context) session.getAttribute("context");
		String[] roleIDs = context.getRoleIDs();
		if (roleIDs != null)
			conditions.put("roleIDs", roleIDs);

		return bean.page(first, limit, sort, dir, conditions, null);
	}

	@JSON
	@RequestMapping(value = "/system/module/tree.json")
	@SuppressWarnings("unchecked")
	public List<ModuleTree> tree(
			@RequestParam(value = "parentID") String parentID,
			@RequestParam(value = "rootID", required = false) String rootID,
			@RequestParam(value = "checked", required = false) boolean checked,
			@RequestParam(value = "roleID", required = false) String roleID,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();
		if (parentID != null && !"module_root".equals(parentID)
				&& !"button_root".equals(parentID)
				&& !"function_root".equals(parentID)
				&& !"rule_root".equals(parentID))
			conditions.put("parentID", parentID);
		else
			conditions.put("noParentID", null);

		if (rootID != null)
			conditions.put("rootID", rootID);

		Context context = (Context) session.getAttribute("context");
		String[] roleIDs = context.getRoleIDs();
		if (roleIDs != null)
			conditions.put("roleIDs", roleIDs);

		return bean.tree(conditions);
	}

	@JSON
	@RequestMapping(value = "/system/module/treeGrid.json")
	public List<ModuleCheckedTree> treeGrid(
			@RequestParam(value = "parentID") String parentID,
			@RequestParam(value = "rootID", required = false) String rootID,
			@RequestParam(value = "roleID") String roleID,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) throws Exception {
		Map<String, Object> conditions = new HashMap<String, Object>();

		if (parentID != null && !"module_root".equals(parentID)
				&& !"button_root".equals(parentID)
				&& !"function_root".equals(parentID)
				&& !"rule_root".equals(parentID))
			conditions.put("parentID", parentID);
		else
			conditions.put("noParentID", null);

		if (rootID != null)
			conditions.put("rootID", rootID);

		if (roleID != null)
			conditions.put("roleID", roleID);

		Context context = (Context) session.getAttribute("context");
		String[] roleIDs = context.getRoleIDs();
		if (roleIDs != null)
			conditions.put("roleIDs", roleIDs);

		return bean.treeGrid(conditions);
	}

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Module.class, new JSONEditor(Module.class));
	}

}
